package net.itbull.alipay.service;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AlipayServiceImpl implements AlipayService {
    Logger log = LoggerFactory.getLogger(AlipayServiceImpl.class);
    @Value("${alipay.returnUrl}")
    private String returnUrl;

    /**
     * web端订单支付
     *
     * @param outTradeNo  订单编号（唯一）
     * @param totalAmount 订单价格
     * @param subject     商品名称
     */
    @Override
    public String webPagePay(String subject, String outTradeNo, String totalAmount) {
        try {
            AlipayTradePagePayResponse response = Factory.Payment.Page()
                    .pay(subject, outTradeNo, totalAmount, returnUrl);
            if (ResponseChecker.success(response)) {
                log.info("调用成功");
                return response.getBody();
            } else {
                log.error("调用失败，原因" + response.getBody());
            }
        } catch (Exception e) {
            log.error("调用发生异常，原因" + e.getMessage());
        }
        return null;
    }

    /**
     * 支付异步回调
     * @param request
     * @return
     */
    @Override
    public String notifyUrl(HttpServletRequest request) {
        Map<String, String> map = new HashMap();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();
            String value = request.getParameter(key);
            map.put(key, value);
        }
        //验签
        try {
            if (Factory.Payment.Common().verifyNotify(map)) {
                log.info("异步通知验签通过");
                //验证用户的支付结果
                String trade_status = request.getParameter("trade_status");
                if (trade_status.equals("TRADE_SUCCESS")) {
                    log.info("支付交易成功");
                    //TODO 更新订单支付状态.....
                }

            } else {
                log.error("异步通知验签失败");
                return "fail";
            }
        } catch (Exception e) {
            log.error("异步发生异常{}", e.getMessage());
            return "fail";
        }
        return "success";
    }

    /**
     * 支付同步步回调
     * @param request
     * @return
     */
    @Override
    public Map<String, String[]> returnUrl(HttpServletRequest request) {
        return request.getParameterMap();
    }

    /**
     * 交易查询
     *
     * @param outTradeNo 订单编号
     * @param outTradeNo 交易号
     */
    @Override
    public String tradeQuery(String outTradeNo, String tradeNo) {
        try {
            AlipayTradeQueryResponse response = Factory.Payment.Common().optional("trade_no", tradeNo)
                    .query(outTradeNo);
            return response.getHttpBody();
        } catch (Exception e) {
            log.error("调用发生异常,原因{}", e.getMessage());
        }
        return null;
    }

    /**
     * 退款
     *
     * @param outTradeNo   订单编号
     * @param outTradeNo   交易号
     * @param refundAmount 退款金额
     * @param outRequestNo 标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
     */
    @Override
    public String refund(String outTradeNo, String tradeNo, String refundAmount, String outRequestNo) {
        try {
            AlipayTradeRefundResponse response = Factory.Payment.Common()
                    .optional("trade_no", tradeNo)
                    .optional("out_request_no", outRequestNo)
                    .refund(outTradeNo, refundAmount);
            if (ResponseChecker.success(response)) {
                return response.getHttpBody();
            } else {
                log.error("调用失败，原因{}", response.getHttpBody());
            }
        } catch (Exception e) {
            log.error("调用发生异常，原因{}", e.getStackTrace());
        }
        return null;
    }

    /**
     * 退款查询
     *
     * @param outTradeNo   订单编号（唯一）
     * @param tradeNo       交易号
     * @param outRequestNo 标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
     */
    @Override
    public String refundQuery(String outTradeNo, String tradeNo, String outRequestNo) {
        try {
            AlipayTradeFastpayRefundQueryResponse response = Factory.Payment.Common()
                    .optional("trade_no", tradeNo)
                    .queryRefund(outTradeNo, outRequestNo);
            return response.httpBody;
        } catch (Exception e) {
            log.error("查询发生异常，原因{}", e.getStackTrace());
        }
        return null;
    }

}
